package com.jf.springmvc.datavalid;

import com.jf.springmvc.datavalid.bean.Person;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-11-01
 * Time:0:02
 */
@RequestMapping("/person")
@Controller
public class PersonHandler {
    @GetMapping("page")
    public String page(HttpServletRequest request) {
        request.setAttribute("person", new Person());
        return "datavalid/add_person";
    }

    @PostMapping("add")
    public String add(@Valid Person person, Errors errors, Map<String, Object> model) {
        System.out.println("==========person=========");
        System.out.println(person);
        System.out.println("==========model=========");
        for (Map.Entry<String, Object> entry : model.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
        if (errors.hasErrors()) {
            System.out.println("==========errors=========");
            List<ObjectError> allErrors = errors.getAllErrors();
            for (ObjectError error : allErrors) {
                System.out.println("error=" + error);
            }
            return "datavalid/add_person";
        }
        return "success";
    }
    /*
    @InitBinder可以绑定一个方法,对WebDataBinder初始化
    1.该方法返回值为void
    2.WebDataBinder是DataBinder的子类,作用为实现表单提交属性封装成Bean
    3.可以通过设置WebDataBinder,取消对某个属性(提交数据)的绑定设置
        若取消DataBinder的属性绑定,在Bean字段的验证注解也应删去(大多数情况验证报错)
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields("id");
    }
}
